package com.leetcode.search.backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Dennis Li
 * @date 2020/7/27 19:12
 */
public class SubsetsWithDup_90 {

    private final List<List<Integer>> res = new ArrayList<>();
    private int[] nums;
    private boolean[] visited;

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        if(nums == null || nums.length == 0) return res;
        Arrays.sort(nums);
        this.nums = nums;
        visited = new boolean[nums.length];
        backtrack(new LinkedList<>(), 0);
        return res;
    }

    private void backtrack(LinkedList<Integer> track, int start) {
        res.add(new ArrayList<>(track));
        for (int i = start; i < nums.length; i++) {
            if(i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) continue;
            visited[i] = true;
            track.add(i);
            backtrack(track, i + 1);
            track.removeLast();
            visited[i] = false;
        }
    }

}
